package com.gitee.hermer.engine.jars.core.web.resource.configuration;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.gitee.hermer.boot.jee.commons.collection.CollectionUtils;
import com.gitee.hermer.boot.jee.commons.collection.StringCache;
import com.gitee.hermer.engine.jars.core.web.config.ResourceProperties;
import com.gitee.hermer.engine.jars.core.web.config.ViewProperties;
import com.gitee.hermer.engine.jars.core.web.resource.ResourceHttpRequestHandler;
import com.gitee.hermer.engine.jars.dependent.dsm.IEnginePropertiesAware;

@Configuration
public class EngineResourceAutoConfiguration extends WebMvcConfigurerAdapter implements IEnginePropertiesAware<ResourceProperties>{

	
	@Bean
	public SimpleUrlHandlerMapping simpleUrlHandlerMapping(ResourceHttpRequestHandler requestHandler,ResourceProperties properties) {
		SimpleUrlHandlerMapping simpleUrlHandlerMapping= new SimpleUrlHandlerMapping();
		Map<String, Object> urlMap = new HashMap<>();
		for (String url : properties.getLocationsArray()) {
			urlMap.put(getMappingHandlerUrl(url), requestHandler);
		}
		simpleUrlHandlerMapping.setUrlMap(urlMap);
		simpleUrlHandlerMapping.setOrder(0);
		return simpleUrlHandlerMapping;
	}
	
	
	
	String getMappingHandlerUrl(String url){
		return new StringCache(url).append("**").toString();
	}
	@Bean
	public ResourceHttpRequestHandler requestHandler(ResourceProperties properties) {
		try{
			ResourceHttpRequestHandler handler= new ResourceHttpRequestHandler();
			handler.setLocationValues(CollectionUtils.newArrayList(properties.getLocationsArray()));
			if(properties.getEnable()){
				handler.setCacheSeconds(properties.getExpire());
				handler.setUseExpiresHeader(true);
				handler.setUseCacheControlNoStore(true);
			}
			return handler;
		}catch (Exception e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

	@Override
	public void setProperties(ResourceProperties properties) {

	}



}
